package crypto

import (
	"fmt"
	"log"
	"net"

	"crypto/tls"
)

func NewTls() *tlsHelper {
	return &tlsHelper{}
}

type tlsHelper struct{}

func (r *tlsHelper) Test() {
	// suites := tls.CipherSuites()
	// suites := tls.InsecureCipherSuites()
	// suiteName := tls.CipherSuiteName(0x002f)
}
func (r *tlsHelper) Server() {
	var ecdsaCertPEM = `-----BEGIN CERTIFICATE-----
MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG
EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk
Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR
lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl
01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8
XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo
A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb
H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1
+jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA==
-----END CERTIFICATE-----
`
	var ecdsaKeyPEM = `-----BEGIN EC PARAMETERS-----
BgUrgQQAIw==
-----END EC PARAMETERS-----
-----BEGIN EC TESTING KEY-----
MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0
NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL
06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz
VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q
kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ==
-----END EC TESTING KEY-----
`
	pem := []byte(ecdsaCertPEM + ecdsaKeyPEM)
	cert, err := tls.X509KeyPair(pem, pem)
	// cert, err := tls.LoadX509KeyPair("backend.crt", "backend.key5")
	if err != nil {
		panic(err)
	}

	// listener, err := net.Listen("tcp", ":8080")
	// if err != nil {
	// 	panic(err)
	// }
	// defer func(listener net.Listener) {
	// 	err := listener.Close()
	// 	if err != nil {
	// 		panic(err)
	// 	}
	// }(listener)
	//
	// tlsListener := tls.NewListener(listener, &tls.Config{
	// 	Certificates: []tls.Certificate{cert},
	// })
	listener, err := tls.Listen("tcp", ":8080", &tls.Config{
		Certificates: []tls.Certificate{cert},
	})

	for {
		conn, err := listener.Accept()
		// conn, err := tlsListener.Accept()
		if err != nil {
			log.Println("Error accepting connection:", err)
			continue
		}

		go handleConnection(conn)
	}
}
func (r *tlsHelper) Client() {
	cache := tls.NewLRUClientSessionCache(1000)
	// conn, err := tls.Dial("tcp", "example.com:443", &tls.Config{
	// 	InsecureSkipVerify: true,
	// 	ClientSessionCache: cache,
	// })
	conn, err := tls.DialWithDialer(&net.Dialer{}, "tcp", "example.com:443", &tls.Config{
		InsecureSkipVerify: true,
		ClientSessionCache: cache,
	})

	if err != nil {
		panic(err)
	}
	defer func(conn *tls.Conn) {
		err := conn.Close()
		if err != nil {
			panic(err)
		}
	}(conn)

	_, err = conn.Write([]byte("Hello, TLS Server!"))
	if err != nil {
		panic(err)
	}

	buffer := make([]byte, 1024)
	n, err := conn.Read(buffer)
	if err != nil {
		panic(err)
	}

	fmt.Println("Received from backend:", string(buffer[:n]))
}

func handleConnection(conn net.Conn) {
	defer func(conn net.Conn) {
		err := conn.Close()
		if err != nil {
			panic(err)
		}
	}(conn)

	tlsConn := tls.Server(conn, &tls.Config{
		InsecureSkipVerify: true,
	})
	defer func(tlsConn *tls.Conn) {
		err := tlsConn.Close()
		if err != nil {
			panic(err)
		}
	}(tlsConn)

	buffer := make([]byte, 1024)
	n, err := tlsConn.Read(buffer)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Received: %s\n", buffer[:n])
	response := "Hello from the backend!"

	_, err = tlsConn.Write([]byte(response))
	if err != nil {
		panic(err)
	}
}
